from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from gironimo.settings import MEDIA_ROOT
from django.conf import settings
from django.middleware.csrf import get_token
from gironimo.gallery.models import Album, Picture
from django.forms.models import modelformset_factory, inlineformset_factory


def index(request):
    '''
        Shows all available galleries
    '''
    galleries = Album.objects.all()
    return render_to_response('gallery/index.html',{
    'galleries': galleries}, context_instance=RequestContext(request))

def detail(request, slug):
    '''
        Detail page for an gallery
        
        Every image within the gallery will be displayd, if user is logged in
        he can edit his gallery
    '''
    gallery = Album.objects.get(slug=slug)
    
    user = gallery.user.get_profile()
    
    admin = False
    if (request.user == gallery.user ):
        admin = True
        
    return render_to_response('gallery/detail.html', {
        'gallery': gallery,
        'admin': admin,
        'gallery_user': user
    }, context_instance=RequestContext(request))

@login_required
def new(request):
    '''
        Creates a new gallery and redirects to picture upload
    '''
    from gironimo.gallery.forms import AlbumForm
    from django.template.defaultfilters import slugify
    
    if request.method == 'POST':
        form = AlbumForm(request.POST)
        if form.is_valid():
            gallery = form.save(commit=False)
            gallery.user = request.user
            gallery.slug = slugify(form.cleaned_data['name'])
            gallery.save()
            return HttpResponseRedirect(reverse('gallery_add', kwargs={'slug':gallery.slug}))
    else:
        form = AlbumForm()
    
    return render_to_response('gallery/new.html', {
    'form': form}, context_instance=RequestContext(request))

@login_required
def add(request, slug):
    '''
        Adds new images to a given gallery, only authenticated access
    '''
    if request.method == 'POST':
        album = Album.objects.get(slug=slug)
        for field_name in request.FILES:
            image = request.FILES[field_name]
            
            picture = Picture.objects.create(album=album, image=image)
            picture.save()
        
        # say ok to SWFUploader
        return HttpResponse("ok", mimetype="text/plain")
    
    else:
        return render_to_response('gallery/add.html', {
            'slug': slug, 
            'csrf_token': get_token(request)
        }, context_instance=RequestContext(request))

@login_required
def edit(request, slug):
    '''
        Edits picture content, tags and so on, even picture can be deleted
    '''
    PictureFormset = inlineformset_factory(Album, Picture, extra=0)
    gallery = Album.objects.get(slug=slug)
    
    if request.method == 'POST':
        formset = PictureFormset(request.POST, request.FILES, instance=gallery)
        if formset.is_valid():
            formset.save()
            return HttpResponseRedirect(reverse('gallery_detail', kwargs={'slug':slug}))
    else:
        formset = PictureFormset(instance=gallery)
    
    return render_to_response('gallery/edit.html', {
    'formset': formset, 'gallery': gallery}, context_instance=RequestContext(request))

@login_required
def edit_info(request, slug):
    '''
        Edits gallery information
    '''
    from gironimo.gallery.forms import AlbumForm
    
    gallery = Album.objects.get(slug=slug)
    
    if request.method == 'POST':
        form = AlbumForm(request.POST, instance=gallery)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('gallery_detail', kwargs={'slug': slug}))
    else:
        form = AlbumForm(instance=gallery)
    
    return render_to_response('gallery/edit_info.html', {
    'form': form, 'gallery': gallery}, context_instance=RequestContext(request))

